package com.ruoyi.framework.interceptor;

import com.ruoyi.common.constant.RedisConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.receipt.context.UserContextHolder;
import com.ruoyi.receipt.domain.TbUser;
import com.ruoyi.receipt.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token拦截器
 *
 * @author chenjian
 */

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String token = request.getHeader("token");

        //未登录时直接放行
        if(null==token){
            return true;
        }

        String userId = jwtUtils.parseToken(token);

        //未查询到用户,即未登录或者登录信息过期
        TbUser curUser=redisCache.getCacheObject(RedisConstants.RECEPTION_TOKEN_CONSTANT+userId);
        if(null==curUser){
            return true;
        }

        //如果带着token,并且是有效地话,自动续期
        redisCache.expire(RedisConstants.RECEPTION_TOKEN_CONSTANT+token,RedisConstants.RECEPTION_TOKEN_TIMEOUT_CONSTANT, RedisConstants.RECEPTION_TOKEN_TIMEUNIT_CONSTANT);

        //将用户压入当前线程
        UserContextHolder.setUser(curUser);

        return true;
    }

}
